package com.files.service.impl;

import com.files.ReturnT;
import com.files.config.FileConfig;
import com.files.exception.FileException;
import com.files.model.FileInfo;
import com.files.service.FileServcie;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Service
@Slf4j
public class DiskFileServiceImpl implements FileServcie {

    @Autowired
    FileConfig fileConfig;

    @Override
    public ReturnT<FileInfo> upload(FileInfo fileInfo) {
        log.info("文件上传==:{}",fileInfo);
        String filename = StringUtils.cleanPath(fileInfo.getOriginalFilename());
        try (InputStream inputStream = fileInfo.getInputStream()) {
            Files.copy(inputStream, Paths.get(this.fileConfig.getDiskPath()).resolve(filename),
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new FileException("Failed to store file " + filename, e);
        }
        return ReturnT.returnOK(fileInfo,"成功");
    }


}
